﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.Common;

using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.ContentManagementFramework.Domain;
using System.IO;

namespace Fuse8.ContentManagementFramework.Web.Etc
{
    public static class CmsTemplateRegionResolver
    {
        private static readonly Regex _razorRegionFinder = new Regex(@"(@RenderRegion\((.*?)\))", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);

        public static ICmsContext Context
        {
            get
            {
                return DependencyServiceLocator.Current.GetInstance<ICmsContext>();
            }
        }

        public static IList<string> ResolveRegionsFromTemplate(CmsTemplateTypeKind templateType, string templatePath)
        {
            Guard.ArgumentNotEmpty(templatePath, "templatePath");

            IList<string> result = null;

            switch (templateType)
            {
                case CmsTemplateTypeKind.MvcRazor:
                    result = ResolveRazorTemplate(templatePath);
                    break;
            }

            return result ?? new List<string>();
        }

        private static IList<string> ResolveRazorTemplate(string templatePath)
        {
            IList<string> result = new List<string>();

            string templateContent = ReadTemplateContent(templatePath);

            var match = _razorRegionFinder.Match(templateContent);

            while (match.Success)
            {
                var matchGroups = match.Groups;
                if (matchGroups.Count == 3) //magic number, depends on regex
                {
                    var group = match.Groups[2];
                    if (group.Success)
                    {
                        result.Add(group.Value.Trim(new char[] { '"' }));
                    }
                }
                match = match.NextMatch();
            }

            return result;
        }

        private static string ReadTemplateContent(string templatePath)
        {
            string result = string.Empty;

            string filePath = Context.MapPath(templatePath);

            using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }

            return result;
        }
    }
}
